import 'dart:math';
import '../models/pet.dart';
import '../models/post.dart';
import '../models/user.dart';
import '../models/video.dart';

enum SearchType {
  all,
  pets,
  posts,
  videos,
  users
}

class SearchResult {
  final List<Pet> pets;
  final List<Post> posts;
  final List<Video> videos;
  final List<User> users;

  SearchResult({
    this.pets = const [],
    this.posts = const [],
    this.videos = const [],
    this.users = const [],
  });

  bool get isEmpty => pets.isEmpty && posts.isEmpty && videos.isEmpty && users.isEmpty;
  int get totalCount => pets.length + posts.length + videos.length + users.length;
}

class SearchService {
  // 模拟搜索方法
  Future<SearchResult> search(String query, {SearchType type = SearchType.all}) async {
    // 模拟API延迟
    await Future.delayed(Duration(milliseconds: 800));
    
    if (query.isEmpty) {
      return SearchResult();
    }
    
    // 转换为小写以便不区分大小写搜索
    final lowercaseQuery = query.toLowerCase();
    
    // 初始化结果对象
    final result = SearchResult(
      pets: type == SearchType.all || type == SearchType.pets ? _searchPets(lowercaseQuery) : [],
      posts: type == SearchType.all || type == SearchType.posts ? _searchPosts(lowercaseQuery) : [],
      videos: type == SearchType.all || type == SearchType.videos ? _searchVideos(lowercaseQuery) : [],
      users: type == SearchType.all || type == SearchType.users ? _searchUsers(lowercaseQuery) : [],
    );
    
    return result;
  }
  
  // 模拟搜索宠物
  List<Pet> _searchPets(String query) {
    final random = Random();
    final List<Pet> results = [];
    
    // 宠物名称列表
    final petNames = ['小黑', '咪咪', '豆豆', '花花', '点点', '贝贝', '球球', '奇奇', '皮皮'];
    final petBreeds = ['金毛', '拉布拉多', '柯基', '哈士奇', '泰迪', '美短', '布偶', '英短', '波斯猫'];
    
    // 模拟匹配结果
    for (var name in petNames) {
      if (name.toLowerCase().contains(query) || random.nextBool()) {
        // 随机生成宠物品种
        final breed = petBreeds[random.nextInt(petBreeds.length)];
        // 生成模拟宠物数据
        results.add(
          Pet(
            id: 'pet_${results.length + 1}',
            name: name,
            species: random.nextBool() ? '猫' : '狗',
            breed: breed,
            age: random.nextInt(10) + 1,
            gender: random.nextBool() ? '公' : '母',
            description: '这是一只可爱的${name}，品种是${breed}',
            images: [
              'https://source.unsplash.com/300x300/?${random.nextBool() ? 'cat' : 'dog'},${results.length + 1}',
            ],
            ownerId: 'user_${random.nextInt(100)}',
            ownerName: '用户${random.nextInt(1000)}',
            ownerAvatar: 'https://randomuser.me/api/portraits/${random.nextBool() ? 'men' : 'women'}/${random.nextInt(100)}.jpg',
            location: '城市${random.nextInt(10) + 1}',
            createdAt: DateTime.now().subtract(Duration(days: random.nextInt(30))),
          ),
        );
      }
    }
    
    // 限制结果数量
    return results.take(min(5, results.length)).toList();
  }
  
  // 模拟搜索帖子
  List<Post> _searchPosts(String query) {
    final random = Random();
    final List<Post> results = [];
    
    // 帖子标题列表
    final postTitles = [
      '如何照顾新领养的猫咪',
      '狗狗的日常训练',
      '宠物的健康饮食',
      '猫咪的有趣行为',
      '带宠物旅行的小技巧',
      '宠物摄影分享',
      '我家狗狗的成长日记',
      '寻找宠物的好去处',
      '宠物美容小贴士',
    ];
    
    // 模拟匹配结果
    for (var title in postTitles) {
      if (title.toLowerCase().contains(query) || random.nextBool()) {
        // 生成模拟帖子数据
        results.add(
          Post(
            id: 'post_${results.length + 1}',
            title: title,
            content: '这是关于${title}的内容，希望对大家有所帮助...',
            images: random.nextBool() 
                ? ['https://source.unsplash.com/300x300/?pet,${results.length + 1}']
                : [],
            userId: 'user_${random.nextInt(100)}',
            userName: '用户${random.nextInt(1000)}',
            userAvatar: 'https://randomuser.me/api/portraits/${random.nextBool() ? 'men' : 'women'}/${random.nextInt(100)}.jpg',
            likes: random.nextInt(100),
            comments: random.nextInt(50),
            createdAt: DateTime.now().subtract(Duration(days: random.nextInt(30))),
          ),
        );
      }
    }
    
    // 限制结果数量
    return results.take(min(5, results.length)).toList();
  }
  
  // 模拟搜索视频
  List<Video> _searchVideos(String query) {
    final random = Random();
    final List<Video> results = [];
    
    // 视频标题列表
    final videoTitles = [
      '猫咪的搞笑瞬间',
      '狗狗的聪明表演',
      '宠物的日常生活',
      '与宠物的互动游戏',
      '宠物的可爱瞬间',
      '宠物的特殊技能',
      '宠物的萌萌哒表情',
      '宠物的户外活动',
      '宠物间的友谊',
    ];
    
    // 模拟匹配结果
    for (var title in videoTitles) {
      if (title.toLowerCase().contains(query) || random.nextBool()) {
        // 生成模拟视频数据
        results.add(
          Video(
            id: 'video_${results.length + 1}',
            title: title,
            description: '这是一段关于${title}的视频，欢迎观看',
            videoUrl: 'https://example.com/videos/${results.length + 1}',
            coverUrl: 'https://source.unsplash.com/300x200/?pet,video,${results.length + 1}',
            duration: random.nextInt(180) + 30, // 30-210秒
            userId: 'user_${random.nextInt(100)}',
            userName: '用户${random.nextInt(1000)}',
            userAvatar: 'https://randomuser.me/api/portraits/${random.nextBool() ? 'men' : 'women'}/${random.nextInt(100)}.jpg',
            views: random.nextInt(1000),
            likes: random.nextInt(200),
            comments: random.nextInt(100),
            createdAt: DateTime.now().subtract(Duration(days: random.nextInt(30))),
          ),
        );
      }
    }
    
    // 限制结果数量
    return results.take(min(5, results.length)).toList();
  }
  
  // 模拟搜索用户
  List<User> _searchUsers(String query) {
    final random = Random();
    final List<User> results = [];
    
    // 用户名列表
    final usernames = [
      '宠物爱好者',
      '猫咪铲屎官',
      '汪星人',
      '萌宠达人',
      '宠物摄影师',
      '爱宠人士',
      '宠物训练师',
      '撸猫达人',
      '爱狗之人',
    ];
    
    // 模拟匹配结果
    for (var username in usernames) {
      if (username.toLowerCase().contains(query) || random.nextBool()) {
        // 生成模拟用户数据
        results.add(
          User(
            id: 'user_${results.length + 1}',
            username: username + random.nextInt(100).toString(),
            avatar: 'https://randomuser.me/api/portraits/${random.nextBool() ? 'men' : 'women'}/${random.nextInt(100)}.jpg',
            bio: random.nextBool() ? '热爱宠物的${random.nextBool() ? '猫奴' : '狗奴'}' : null,
            following: List.generate(random.nextInt(20), (index) => 'user_${random.nextInt(100)}'),
            followers: List.generate(random.nextInt(50), (index) => 'user_${random.nextInt(100)}'),
            statistics: {
              'pets': random.nextInt(5),
              'posts': random.nextInt(50),
              'videos': random.nextInt(10),
            },
          ),
        );
      }
    }
    
    // 限制结果数量
    return results.take(min(5, results.length)).toList();
  }
  
  // 获取搜索历史
  Future<List<String>> getSearchHistory() async {
    // 模拟API延迟
    await Future.delayed(Duration(milliseconds: 300));
    
    // 返回模拟的搜索历史
    return [
      '金毛',
      '猫咪行为',
      '狗狗训练',
      '宠物美容',
      '布偶猫',
      '宠物玩具',
    ];
  }
  
  // 清除搜索历史
  Future<bool> clearSearchHistory() async {
    // 模拟API延迟
    await Future.delayed(Duration(milliseconds: 300));
    
    // 模拟成功响应
    return true;
  }
  
  // 保存搜索关键词
  Future<bool> saveSearchQuery(String query) async {
    // 模拟API延迟
    await Future.delayed(Duration(milliseconds: 200));
    
    // 模拟成功响应
    return true;
  }
} 